<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<view class="nav-bar">
			<view class="status-bar" :style="{height: statusBarHeight + 'px'}"></view>
			<view class="nav-content">
				<view class="nav-left" @click="goBack">
					<u-icon name="arrow-left" color="#333" size="18"></u-icon>
				</view>
				<view class="nav-title">确认订单</view>
				<view class="nav-right"></view>
			</view>
		</view>
		
		<!-- 收货地址 -->
		<view class="address-section" :style="{marginTop: (statusBarHeight + 44) + 'px'}" @click="goToSelectAddress">
			<view class="address-content" v-if="selectedAddress">
				<view class="address-info">
					<view class="user-info">
						<text class="name">{{selectedAddress.addressName}}</text>
						<text class="phone">{{selectedAddress.addressPhone}}</text>
					</view>
					<view class="address-detail">{{selectedAddress.addressInfo}} {{selectedAddress.addressCommunity}}</view>
				</view>
				<view class="address-arrow">
					<u-icon name="arrow-right" color="#999" size="28"></u-icon>
				</view>
			</view>
			<view class="no-address" v-else>
				<text>请选择收货地址</text>
				<view class="address-arrow">
					<u-icon name="arrow-right" color="#999" size="28"></u-icon>
				</view>
			</view>
		</view>
		
		<!-- 商品信息 -->
		<view class="order-section">
			<view class="section-title">商品信息</view>
			<view class="product-item">
				<image class="product-image" :src="productInfo.image" mode="aspectFill"></image>
				<view class="product-detail">
					<view class="product-name">{{productInfo.name}}</view>
					<view class="product-price">{{productInfo.points}} 积分</view>
					<view class="product-quantity">x 1</view>
				</view>
			</view>
		</view>
		
		<!-- 订单备注 -->
		<view class="remark-section">
			<view class="section-title">订单备注</view>
			<view class="remark-input">
				<input type="text" v-model="remark" placeholder="请输入备注信息（选填）" />
			</view>
		</view>
		
		<!-- 底部操作栏 -->
		<view class="footer">
			<view class="total-points">
				消耗积分: <text class="points-value">{{productInfo.points}}</text>
			</view>
			<view class="submit-btn" @click="submitOrder">
				确认兑换
			</view>
		</view>
	</view>
</template>

<script>
import request from '@/util/request.js'

export default {
	data() {
		return {
			statusBarHeight: 0,
			orderNum: '', // 订单号
			productInfo: {
				productId: '',
				name: '',
				points: 0,
				image: ''
			},
			selectedAddress: null,
			remark: '',
			userInfo: {
				userId: '',
				userAcc: '',
				userName: ''
			}
		}
	},
	onLoad(options) {
		// 获取状态栏高度
		const systemInfo = uni.getSystemInfoSync();
		this.statusBarHeight = systemInfo.statusBarHeight;
		
		// 获取商品信息
		if (options) {
			// 优先从IntegralDetail页面传递的完整商品数据获取
			if (options.productData) {
				try {
					const productData = JSON.parse(decodeURIComponent(options.productData));
					this.productInfo.productId = productData.id || '';
					this.productInfo.name = productData.name || '';
					this.productInfo.points = productData.points || 0;
					this.productInfo.image = productData.image || '';
					console.log('从IntegralDetail获取的商品信息:', this.productInfo);
				} catch (error) {
					console.error('解析商品数据失败:', error);
					// 如果解析失败，尝试从单独的参数获取
					this.getProductInfoFromParams(options);
				}
			} else {
				// 兼容旧的参数传递方式
				this.getProductInfoFromParams(options);
			}
		}
		
		// 获取用户信息
		this.getUserInfo();
		
		// 生成订单号
		this.generateOrderNum();
		
		// 获取默认地址
		this.getDefaultAddress();
	},
	onShow() {
		// 页面显示时，检查是否有新选择的地址
		const address = uni.getStorageSync('selectedAddress');
		if (address) {
			this.selectedAddress = address;
			uni.removeStorageSync('selectedAddress'); // 使用后清除
		}
	},
	methods: {
		goBack() {
			uni.navigateBack();
		},
		// 生成订单号
		async generateOrderNum() {
			try {
				console.log('开始生成订单号...');
				const res = await request({
					url: '/score-service/score-order/generateOrderNum',
					method: 'GET'
				});
				
				console.log('订单号生成接口返回:', res);
				
				if (res.success && res.data && res.data.orderNum) {
					this.orderNum = res.data.orderNum;
					console.log('订单号生成成功:', this.orderNum);
				} else {
					console.error('订单号生成失败:', res.message);
					uni.showToast({
						title: res.message || '订单号生成失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('生成订单号异常:', error);
				uni.showToast({
					title: '订单号生成失败',
					icon: 'none'
				});
			}
		},
		// 从单独的参数获取商品信息
		getProductInfoFromParams(options) {
			this.productInfo.productId = options.productId || '';
			this.productInfo.name = decodeURIComponent(options.name || '');
			this.productInfo.points = options.points || 0;
			this.productInfo.image = decodeURIComponent(options.image || '');
			console.log('从单独参数获取的商品信息:', this.productInfo);
		},
		// 获取用户信息
		getUserInfo() {
			try {
				const userInfo = uni.getStorageSync('userInfo');
				if (userInfo) {
					this.userInfo.userId = userInfo.userId;
					this.userInfo.userAcc = userInfo.userAcc;
					this.userInfo.userName = userInfo.userName;
				} else {
					// 未登录处理
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}
			} catch (e) {
				console.error('获取用户信息失败', e);
			}
		},
		// 获取默认地址
		async getDefaultAddress() {
			try {
				const res = await request({
					url: `/user-service/address/list?userId=${this.userInfo.userId}`,
					method: 'GET'
				});
				
				if (res.data && res.data.list && res.data.list.length > 0) {
					// 查找默认地址
					const defaultAddress = res.data.list.find(item => item.addressDefault == 1);
					if (defaultAddress) {
						this.selectedAddress = defaultAddress;
					} else {
						// 如果没有默认地址，使用第一个地址
						this.selectedAddress = res.data.list[0];
					}
				}
			} catch (error) {
				console.error('获取默认地址失败', error);
			}
		},
		// 前往选择地址
		goToSelectAddress() {
			uni.navigateTo({
				url: '/pages/address/address'
			});
			
			// 监听地址选择事件
			uni.$once('addressSelected', (address) => {
				this.selectedAddress = address;
			});
		},
		// 提交订单 - 调用后端积分支付接口
		async submitOrder() {
			try {
				// 1. 参数验证
				if (!this.orderNum) {
					uni.showToast({
						title: '订单号未生成，请重试',
						icon: 'none'
					});
					return;
				}
				
				if (!this.selectedAddress) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					});
					return;
				}
				
				if (!this.userInfo.userId) {
					uni.showToast({
						title: '用户信息异常，请重新登录',
						icon: 'none'
					});
					return;
				}
				
				if (!this.productInfo.productId || !this.productInfo.points) {
					uni.showToast({
						title: '商品信息异常',
						icon: 'none'
					});
					return;
				}
				
				// 2. 显示加载状态
				uni.showLoading({
					title: '正在提交订单...'
				});
				
				// 3. 构建符合OrderCreateDto的订单数据
				const orderCreateData = {
					order_num: this.orderNum,                              // 订单号 (String)
					user_id: parseInt(this.userInfo.userId),              // 用户ID (Long)
					order_type: "积分",                                     // 订单类型 (String)
					related_id: parseInt(this.productInfo.productId),     // 关联商品ID (Long)
					order_amount: parseFloat(this.productInfo.points),    // 订单金额-积分 (Double)
					least_time: 0,                                         // 租赁天数 (Integer) - 积分商品不需要
					order_address_id: parseInt(this.selectedAddress.addressId), // 收货地址ID (Long)
					order_quantity: 1                                      // 订单数量 (Integer)
				};
				
				console.log('==== 积分支付订单数据 ====');
				console.log('订单号:', orderCreateData.order_num);
				console.log('用户ID:', orderCreateData.user_id);
				console.log('商品ID:', orderCreateData.related_id);
				console.log('需要积分:', orderCreateData.order_amount);
				console.log('地址ID:', orderCreateData.order_address_id);
				console.log('完整订单数据:', orderCreateData);
				
				// 4. 调用后端积分支付接口
				const response = await request({
					url: '/score-service/score-order/create',
					method: 'POST',
					data: orderCreateData
				});
				
				// 5. 隐藏加载状态
				uni.hideLoading();
				
				console.log('==== 后端支付响应 ====');
				console.log('响应数据:', response);
				
				// 6. 处理支付结果
				if (response.success) {
					// 支付成功
					console.log('==== 积分支付成功 ====');
					console.log('订单ID:', response.data.orderId);
					console.log('订单号:', response.data.orderNum);
					console.log('剩余积分:', response.data.remainingScore);
					
					uni.showModal({
						title: '兑换成功',
						content: `订单号：${response.data.orderNum}\n剩余积分：${response.data.remainingScore}分`,
						showCancel: false,
						confirmText: '确定',
						success: () => {
							// 返回上一页
							uni.navigateBack();
						}
					});
					
				} else {
					// 支付失败
					console.error('==== 积分支付失败 ====');
					console.error('失败原因:', response.message);
					
					uni.showModal({
						title: '兑换失败',
						content: response.message || '积分不足或系统异常，请重试',
						showCancel: false,
						confirmText: '确定'
					});
				}
				
			} catch (error) {
				// 7. 异常处理
				uni.hideLoading();
				
				console.error('==== 积分支付异常 ====');
				console.error('异常信息:', error);
				
				let errorMessage = '网络异常，请检查网络连接';
				if (error.message) {
					errorMessage = error.message;
				} else if (typeof error === 'string') {
					errorMessage = error;
				}
				
				uni.showModal({
					title: '系统异常',
					content: errorMessage,
					showCancel: false,
					confirmText: '确定'
				});
			}
		}
	}
}
</script>

<style lang="scss">
.container {
	min-height: 100vh;
	background-color: #f8f8f8;
	position: relative;
	padding-bottom: 120rpx;
}

/* 自定义导航栏 */
.nav-bar {
	background-color: #ffffff;
	border-bottom: 1rpx solid #f0f0f0;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 1000;
}

.status-bar {
	width: 100%;
	background-color: #ffffff;
}

.nav-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 88rpx;
	padding: 0 30rpx;
	background-color: #ffffff;
}

.nav-left {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
}

.nav-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	text-align: center;
	flex: 1;
}

.nav-right {
	width: 60rpx;
	flex-shrink: 0;
}

.address-section {
	background-color: #ffffff;
	padding: 30rpx;
	
	.address-content {
		display: flex;
		align-items: center;
		
		.address-info {
			flex: 1;
			
			.user-info {
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;
				
				.name {
					font-size: 32rpx;
					font-weight: 500;
					color: #333;
					margin-right: 20rpx;
				}
				
				.phone {
					font-size: 28rpx;
					color: #666;
				}
			}
			
			.address-detail {
				font-size: 28rpx;
				color: #666;
				line-height: 1.5;
			}
		}
	}
	
	.no-address {
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 30rpx;
		color: #999;
	}
	
	.address-arrow {
		margin-left: 20rpx;
	}
}

.order-section {
	background-color: #ffffff;
	padding: 30rpx;
	margin-top: 20rpx;
	
	.section-title {
		font-size: 30rpx;
		color: #333;
		margin-bottom: 20rpx;
		font-weight: 500;
	}
	
	.product-item {
		display: flex;
		align-items: center;
		
		.product-image {
			width: 160rpx;
			height: 160rpx;
			border-radius: 8rpx;
			margin-right: 20rpx;
		}
		
		.product-detail {
			flex: 1;
			position: relative;
			
			.product-name {
				font-size: 28rpx;
				color: #333;
				margin-bottom: 10rpx;
			}
			
			.product-price {
				font-size: 32rpx;
				color: #4CAF50;
				font-weight: 500;
			}
			
			.product-quantity {
				position: absolute;
				right: 0;
				bottom: 0;
				font-size: 28rpx;
				color: #999;
			}
		}
	}
}

.remark-section {
	background-color: #ffffff;
	padding: 30rpx;
	margin-top: 20rpx;
	
	.section-title {
		font-size: 30rpx;
		color: #333;
		margin-bottom: 20rpx;
		font-weight: 500;
	}
	
	.remark-input {
		input {
			width: 100%;
			height: 80rpx;
			background-color: #f8f8f8;
			border-radius: 8rpx;
			padding: 0 20rpx;
			font-size: 28rpx;
		}
	}
}

.footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	
	.total-points {
		flex: 1;
		font-size: 28rpx;
		color: #666;
		
		.points-value {
			font-size: 36rpx;
			color: #4CAF50;
			font-weight: bold;
		}
	}
	
	.submit-btn {
		width: 240rpx;
		height: 80rpx;
		background-color: #4CAF50;
		color: #ffffff;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 8rpx;
	}
}
</style> 